import { copyFile, mkdir, readFile, writeFile } from 'fs/promises'
import { existsSync } from 'fs'
import path from 'path'

export default {
  outputPreset: async (name: string, outputPath = './') => {
    const presetDir = path.join(__dirname, `../preset/${name}.json`)
    return copyFile(presetDir, path.join(outputPath, `./${name}.json`))
  },
  createDir: async (path: string) => {
    if (existsSync(path)) {
      throw new Error('目录名称已经存在')
    }
    return mkdir(path)
  },
  readPreset: async (path: string) => {
    const raw = await readFile(path, { encoding: 'utf8' })
    return JSON.parse(raw)
  },
  outputTemplate: async (name: string, outputPath: string, data: string) => {
    const filePath = path.join(outputPath, name)
    if (existsSync(filePath)) {
      throw new Error(`名称为 ${name} 的文件已经存在`)
    }
    await writeFile(filePath, data)
  }
}